package com.luomu.base.biz.cookBook.redisLock.constant;

import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author admin
 * 是“礼貌请求锁”，等一会儿拿不到就放弃。
 */
@Component
public class RedissonTryLock {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedissonTryLock.class);

    @Resource
    private RedissonClient redissonClient;

    /**
     * 加锁默认时间长
     *    默认不等待
     *    90秒自动解锁
     * @param lockName 加锁key
     *
     */
    public boolean acquireTryLock(String lockName) {
        LOGGER.info("acquireTryLock,lockKey:{}",lockName);
        RLock lock = redissonClient.getLock(lockName);
        try {
            return lock.tryLock(0, 90, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 加锁，设置加锁等待秒数、上锁后自动解锁秒数
     * @param lockName 加锁key
     * @param waitingSeconds
     *        ch: 加锁等待秒数
     *        en: Waiting seconds
     * @param automaticUnlockingSeconds
     *        ch: 上锁后自动解锁秒数
     *        en: Automatic unlocking seconds after locking
     */
    public boolean acquireTryLock(String lockName,long waitingSeconds,long automaticUnlockingSeconds) {
        LOGGER.info("acquireTryLock,lockKey:{},waitingSeconds:{},automaticUnlockingSeconds:{}",lockName,waitingSeconds,automaticUnlockingSeconds);
        RLock lock = redissonClient.getLock(lockName);
        try {
            return lock.tryLock(waitingSeconds, automaticUnlockingSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 释放锁
     * 是否已加锁  并且为当前线程加的锁
     */
    public void releaseLock(RLock lock) {
        LOGGER.info("releaseLock,lockKey:{}",lock != null ? lock.getName():"null");
        try {
            if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        } catch (Exception e) {
            LOGGER.error("releaseLock失败异常,原因:",e);
        }
    }

    /**
     * 释放锁
     */
    public void releaseLock(String lockName) {
        LOGGER.info("releaseLock,lockKey:{}",lockName);
        RLock lock = redissonClient.getLock(lockName);
        if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
            try {
                lock.unlock();
            } catch (Exception e) {
                LOGGER.error("releaseLock失败异常,原因:",e);
            }
        }
    }
}